package com.zx.viewlearn.views;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

/**
 * TODO: document your custom view class.
 */
public class MyView3 extends View {
    public MyView3(Context context) {
        super(context);
        mScroller = new Scroller(context);
    }

    public MyView3(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mScroller = new Scroller(context);
    }

    public MyView3(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mScroller = new Scroller(context);
    }

    Scroller mScroller;

    /**
     * draw方法会调用该方法,通过循环调用，来实现平滑移动
     */
    @Override
    public void computeScroll() {
        super.computeScroll();
        //该方法计算currX,currY，直到移动结束（源码为mFinished==true时候返回false）：如下
//        if (mCurrX == mFinalX && mCurrY == mFinalY) {
//            mFinished = true;
//        }
        if (mScroller.computeScrollOffset()) {

            ((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY());//移动
            invalidate();//重绘页面，会调用draw方法
        }
    }

    public void smoothScrollTo(int destX, int destY) {
        int scrollX = getScrollX();
        int deltaX = destX - scrollX;
        int scrollY = getScrollY();
        int deltaY = destY - scrollY;
        mScroller.startScroll(scrollX, scrollY, deltaX, deltaY, 2000);//会初始化一些值：包括开始位置，最终位置
        invalidate();//重绘页面，会调用draw方法
    }

}
